package com.hefan.robot.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import com.hefan.robot.itf.RobotInitService;
import com.hefan.robot.itf.RobotService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.Map;

/**
 * Created by nigle on 2016/12/7.
 */
@Path("/robot")
@Component("robotInitService")
public class RobotInitServiceImpl implements RobotInitService{

    public Logger logger = LoggerFactory.getLogger(RobotInitServiceImpl.class);

    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    RobotService robotService;
    @Resource
    RoomEnterExitOptService roomEnterExitOptService;

    /**
     * 机器人入redis中List栈初始化任务
     */
    @GET
    @Path("/initRobot")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    public ResultBean initRobotToRedisList(@QueryParam("startTime") String startTime) {
        try {
            logger.info("后台参：startTime：{}",startTime);
            logger.info("新增前机器人hash数量：{}",livingRedisOptService.getWholeRobotCount());
            logger.info("新增前机器人list数量：{}",livingRedisOptService.getWholeRobotIdCount());
            List<Map> list = robotService.getAllRobotList(startTime);
                if(null != list && list.size() > 0){
                    for (Map map : list) {
                        try {
                            String userId = MapUtils.getStrValue(map,"userId","");
                            String robotStr = JSON.toJSONString(map);
                            logger.info("初始化全局机器人  robotStr：" + robotStr);
                            logger.info("返回行数：{}",livingRedisOptService.addWholeRobot(userId, robotStr));
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error("初始化全局机器人  error", e);
                        }
                    }
                }else {
                    logger.info("取全局机器人失败");
                }
            logger.info("新增后机器人hash数量：{}",livingRedisOptService.getWholeRobotCount());
            logger.info("新增后机器人list数量：{}",livingRedisOptService.getWholeRobotIdCount());
        } catch (Exception e) {
            logger.info("机器人入redis中List栈初始化任务出错");
            e.printStackTrace();
            return new ResultBean(ResultCode.UNSUCCESS);
        }
        return new ResultBean(ResultCode.SUCCESS);
    }

    /**
     * redis中清除机器人信息缓存（后台使用）
     */
    @GET
    @Path("/removeRobot")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    public ResultBean removeRobot(@QueryParam("userId") String userId) {
        try {
            if(StringUtils.isBlank(userId)){
                return new ResultBean(ResultCode.ParamException);
            }
            long l = livingRedisOptService.removeRobotInAll(userId);
            logger.info("清除全局机器人{}LIST返回：{}", userId, l);
            String location = livingRedisOptService.getRobotLocation(userId);
            logger.info("lvingredis:::location:{}",location);
            if (StringUtils.isNotBlank(location)) {
                logger.info("查找机器人{}定位：{}", userId, location);
            }
            if ( StringUtils.isNotBlank(location) && !location.equals("0")) {
                roomEnterExitOptService.exitRoom(userId, 0, "", location);
                //离开直播间发送首页检查
                String livingVoStr = livingRedisOptService.getLivingInfo_Hash(location);
                if (StringUtils.isNotBlank(livingVoStr)) {
                    LivingRoomInfoVo livingVo = JSON.parseObject(livingVoStr, LivingRoomInfoVo.class);
                    if (null != livingVo) {
                        roomEnterExitOptService.sendExitRoomMsgQueue(location, livingVo.getChatRoomId(), livingVo.getLiveUuid(), userId);
                    }else {
                        logger.info("直播信息解析失败");
                    }
                }else {
                    logger.info("直播信息获取失败");
                }
                l = livingRedisOptService.removeRobotInRoom(userId, location);
                logger.info("清除直播间机器人{}LIST返回：{}", userId, l);
            }
        } catch (Exception e) {
            logger.info("删除机器人redis中List栈出错");
            e.printStackTrace();
            return new ResultBean(ResultCode.UNSUCCESS);
        }
        return new ResultBean(ResultCode.SUCCESS);
    }

    /**
     * 清理所有机器人信息（redis）
     * 除去直播间内
     */
    @GET
    @Path("/clearRobot")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    public ResultBean removeRobot() {
        livingRedisOptService.clearRobot();
        return new ResultBean(ResultCode.SUCCESS);
    }
}
